package cn.bugio.note.service.content.impl;

import cn.bugio.note.common.domain.dto.ShareDTO;
import cn.bugio.note.common.domain.dto.UserDTO;
import cn.bugio.note.common.vo.ServerResponse;
import cn.bugio.note.dao.content.ShareMapper;
import cn.bugio.note.domain.dto.content.ShareAuditDTO;
import cn.bugio.note.common.domain.messaging.UserAndBonusMsgDTO;
import cn.bugio.note.domain.entity.content.Share;
import cn.bugio.note.feignclient.UserCenterFeignClient;
import cn.bugio.note.service.content.ShareService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author Vincent Vic
 * @version 1.0
 * @Description
 * @since 2021/2/16
 */

@Service("shareService")
@Slf4j
public class ShareServiceImpl implements ShareService {

    @Autowired
    private ShareMapper shareMapper;

    @Autowired
    private UserCenterFeignClient userCenterFeignClient;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 通过id查找Share
     *
     * @return
     */
    @Override
    public ServerResponse<ShareDTO> findById(Integer id) {
        //获取详情
        Share share = shareMapper.selectByPrimaryKey(id);
        if (share == null){
            return ServerResponse.error(id+" 查询不存在");
        }

        log.info("share : {}",share);
        Integer userId = share.getUserId();

//        List<ServiceInstance> instances = discoveryClient.getInstances("user-center");
//        String url = instances.stream()
//                .map(instance -> instance.getUri().toString() + "/users/{id}")
//                .findFirst()
//                .orElseThrow(() -> new IllegalArgumentException("当前没有实例"));
//        log.info("user ip address : {} " , url);

//        ServerResponse serverResponse = restTemplate.getForObject(
//                "http://user-center/users/{id}",//url,
//                ServerResponse.class,userId
//        );

        ServerResponse<UserDTO> userDTOServerResponse = userCenterFeignClient.findById(id);



        log.info("User Server Response :{}",userDTOServerResponse);
//        LinkedHashMap linkedHashMap = (LinkedHashMap)serverResponse.getData();
//        UserDTO userDTO =JSONObject.parseObject(JSONObject.toJSON(linkedHashMap).toString(),UserDTO.class);
        BeanCopier beanCopier = BeanCopier.create(Share.class, ShareDTO.class, false);
        ShareDTO shareDTO = new ShareDTO();
        beanCopier.copy(share,shareDTO,null);

        System.out.println(shareDTO);
        shareDTO.setWxNickname(userDTOServerResponse.getData().getWxNickname());
        return ServerResponse.success(shareDTO);
    }

    @Override
    public ServerResponse<ShareDTO> auditById(Integer id, ShareAuditDTO auditDTO) {
        //1.查询share是否存在，不存在或者当前audit_status != NOT_YET ,那么抛异常
        Share share = shareMapper.selectByPrimaryKey(id);

        System.out.println(share);
        System.out.println(auditDTO);
        if (null == share) {
            throw new IllegalArgumentException("参数非法！该分享不存在！");
        }else if (!Objects.equals("NOT_YET",share.getAuditStatus())) {
            throw new IllegalArgumentException("该分享已审核！");
        }
        //2.审核资源，更新状态
        share.setAuditStatus(auditDTO.getAuditStatusEnum().toString());
        //shareMapper.updateByPrimaryKey(share);

        //3.更新发布人积分,异步实现
        rocketMQTemplate.convertAndSend("add-bonus",
                    UserAndBonusMsgDTO.builder()
                        .userId(share.getUserId())
                        .bonus(50)
                        .build()
                );

        return ServerResponse.success();
    }
}
